package com.upload.util;

import com.upload.bean.yCoin.LoginResponseBean;
import com.upload.service.UserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by asus on 2017/3/23.
 */
@Component
public class CookieUtil {

    /**
     * 获取cookie的value
     * @param request
     * @param key cookie key
     * @return
     */
    public static boolean getCookie(HttpServletRequest request, String key,RedisTemplate<String,LoginResponseBean> redisTemplate){

        Cookie cookie = WebUtils.getCookie(request,"cookieToken");
        if (cookie != null){
            if(redisTemplate.hasKey(cookie.getValue())){
                return true;
            }else{
                return false;
            }
        } else {
            return false;
        }

    }

    public static String getCookie(HttpServletRequest request, String key) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                if (key.equals(cookies[i].getName())) {
                    return cookies[i].getValue();
                }
            }
        }
        return null;
    }

    public static void setCookie(String key, String value,Integer cookieExpireTime, HttpServletResponse response){
        Cookie cookie=new Cookie(key,value);
        cookie.setPath("/");
        cookie.setMaxAge(cookieExpireTime);
        response.addCookie(cookie);
    }
    @Autowired
    private UserInfoService userInfoService;
}
